package com.bckj.fastboot.iot.parse.core.alarmrule;

import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * SpELAlarmRuleConditionInvoker
 *
 * @author wfc
 **/
@Slf4j
@Component
public class SpELAlarmRuleConditionEvaluator implements AlarmRuleConditionEvaluator {

    @Override
    public boolean eval(String condition, Map<String, Object> params) {
        try {
            ExpressionParser parser = new SpelExpressionParser();
            Expression expression = parser.parseExpression(condition);

            StandardEvaluationContext evalContext = new StandardEvaluationContext();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                evalContext.setVariable(entry.getKey(), entry.getValue());
            }
            // 变量名和对象属性对应，比如 temperature 对应 context.getTemperature()
            return Boolean.TRUE.equals(expression.getValue(evalContext, Boolean.class));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false; // 表达式错误时默认不触发
        }
    }
}
